package com.dingreading.cloud.common.util;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.dto.LoginDto;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;

import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录鉴权工具
 */
public class LoginAuthUtil {


    // 门店cookie的key
    public static final String DDPB_TOKEN = "DDPBToken";

    public static final String HTML_URL = "htmlUrl";

    /**
     * 判断是否是叮叮学院
     */
    public static boolean isCourse(String htmlUrl) {
        return htmlUrl.contains("/course");
    }

    /**
     * 获取总部端token
     */
    public static String getAuthorization(HttpHeaders headers) {
        return headers.getFirst("Authorization");
    }

    /**
     * 获取请求页面
     */
    public static String getHtmlUrl(HttpHeaders headers) {
        return headers.getFirst(HTML_URL);
    }

    /**
     * 获取请求页面
     */
    public static String getCookies(MultiValueMap<String, HttpCookie> cookies) {
        HttpCookie cookie = cookies.getFirst(DDPB_TOKEN);
        if (cookie == null)
            return "";

        return cookie.getValue();
    }

    /**
     * 获取请求页面
     */
    public static String getAppId(String htmlUrl) {
        String appId = "";
//        System.out.println("htmlUrl = " + htmlUrl);
        if (htmlUrl.contains("/storeSubject") || htmlUrl.contains("/course")
                || htmlUrl.contains("/douxuehui") || htmlUrl.contains("/hbjd") || htmlUrl.contains("/hsyd")) {
            appId = "lesson";
        } else if (htmlUrl.contains("/mall")) {
            appId = "mall";
        } else if (htmlUrl.contains("/bookManage")) {
            appId = "books";
        } else if (htmlUrl.contains("/soms") || htmlUrl.contains("/contest")|| htmlUrl.contains("/searchMember")) {
            appId = "som";
        }
//        System.out.println("appId = " + appId);
        return appId;
    }

    /**
     * 获取登录地址
     */
    public static String getLoginUrl(String appId, String appSecret, String htmlUrl) {
        String loginUrl = "";
        try {
            String urlFormat = "https://www.dingreading.com/?r=passport/staff/login&appid=%s&callback=%s&ts=%s&signature=%s";
            String ts = System.currentTimeMillis() + "";

            Map<String, String> map = new LinkedHashMap<>();
            map.put("appid", appId);
            map.put("callback", htmlUrl);
            map.put("ts", ts);
            String signature = getSignature(map, appSecret);
            // 拼接登录地址
            loginUrl = String.format(urlFormat, appId, URLEncoder.encode(htmlUrl, "utf-8"), ts, signature);
        } catch (Exception ce) {
            ce.printStackTrace();
        }
        return loginUrl;
    }

    /**
     * 获取用户的登录信息
     */
    public static R<Object> getLoginInfo(String appId, String appSecret, String htmlUrl, String cookieValue, String ip) {


        String urlFormat = "https://www.dingreading.com/?r=passport/staff/getauth&appid=%s&token=%s&ts=%s&signature=%s&ip=%s";
        String ts = System.currentTimeMillis() + "";
        Map<String, String> map = new LinkedHashMap<>();
        map.put("appid", appId);
        map.put("token", cookieValue);
        map.put("ts", ts);
        String signature = getSignature(map, appSecret);
        // 拼接请求地址
        String loginInfoUrl = String.format(urlFormat, appId, cookieValue, ts, signature, ip);
        // 请求用户的信息
        String loginJson = HttpUtils.get(loginInfoUrl);

        if (StringUtils.isBlank(loginJson)) {
            // 请求登录信息失败，去登录
            String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(-1, "登录已失效", loginUrl);
        }

        LoginDto loginDto = JSONObject.parseObject(loginJson, LoginDto.class);
        if (loginDto == null || loginDto.getSt() != 0) {
            // 登录信息失效，去登录
            String msg = loginDto == null ? "用户校验失败" : loginDto.getMsg();
            String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(-1, msg, loginUrl);
        }

        LoginDataDto loginDataDto = loginDto.getData();
        if (loginDataDto == null) {
            String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(4023, "登录用户信息已失效", loginUrl);
        }
        if (loginDataDto.getEnabled() != 1) {
            String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(4023, "当前账号已不可用，请联系与您对接的运营督导", loginUrl);
        }
//            List<String> cooperationTypes = loginDataDto.getCooperationTypes();
//            if (CollectionUtils.isEmpty(cooperationTypes)){
//                String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
//                return R.fail(4023, "门店未分配合作类型", loginUrl);
//            }

        List<String> authApps = loginDataDto.getAuthApps();
        if (CollectionUtils.isEmpty(authApps) || !authApps.contains(appId)) {
            // 判断是否是叮叮学院
            boolean course = LoginAuthUtil.isCourse(htmlUrl);
            if (!course) {
                String loginUrl = getLoginUrl(appId, appSecret, htmlUrl);
                return R.fail(4023, "没有该模块的访问权限", loginUrl);
            }
        }

        return R.ok(loginDataDto);
    }

    /**
     * 生成签名
     */
    private static String getSignature(Map<String, String> map, String appSecret) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String value = entry.getValue();
            if (StringUtils.isNotBlank(value))
                sb.append(value).append("&");
        }
        sb.append(appSecret);

        SHAUtil shaUtil = new SHAUtil();
        return shaUtil.SHA1(sb.toString());
    }

}
